package org.compiere.process;

import java.io.File;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;

import jxl.Sheet;
import jxl.Workbook;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.apps.ADialog;
import org.compiere.model.MAGRAgreement;
import org.compiere.model.MAGRAgreementList;
import org.compiere.model.MAGRApprovalList;
import org.compiere.model.MAGRStage;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPartner;
import org.compiere.model.MUser;
import org.compiere.model.X_CMS_Contract;
import org.compiere.model.X_TRM_Application;
import org.compiere.util.Env;
import org.compiere.util.Msg;

import extend.org.compiere.hrm.ExcelCell;
import extend.org.compiere.utils.Util;

public class TRM_SendNotifyByFinanceApplication extends SvrProcess {
	
	/** Current context */
	private Properties m_ctx;
	private ProcessInfo pi;
	private X_CMS_Contract contract = null;
	private X_TRM_Application application = null;
	private int p_AGR_Stage_ID;
	private int p_AD_Table_ID;
	private int Record_ID;
	private boolean p_isApproved;
	private String templateName = "TRM_SendNotifyByFinanceRequisition";
	private MAGRStage currStage = null;
	private MAGRStage nextStage = null;
	private MAGRStage firstStage = null;
	private int AD_User_ID = 0;
	private ArrayList<Integer> C_BPartner_ID_From;
	private int C_BPartner_ID_To;
	/*
     */
	protected void prepare() {

		log.info("Send Mail: beginning of the FinanceRequisition");
		m_ctx = getCtx();
		pi = getProcessInfo();

		AD_User_ID = Env.getAD_User_ID(getCtx());

		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (name == null)
				;
			else if (name.equals("Record_ID")) {
				Record_ID = para[i].getParameterAsInt();
			} else if (name.equals("AGR_Stage_ID")) {
				p_AGR_Stage_ID = para[i].getParameterAsInt();
			} else if (name.equals("AD_Table_ID")) {
				p_AD_Table_ID = para[i].getParameterAsInt();
			} else if (name.equals("IsApproved")) {
				p_isApproved = para[i].getParameterAsBoolean();
			} else {
				log.log(Level.INFO, "Unknown Parameter: " + name);
			}
		}
		
		currStage = new MAGRStage(m_ctx, p_AGR_Stage_ID, get_TrxName());
		
//		if (p_isApproved && currStage.getNextStage() != null) {
		if (p_isApproved && !currStage.isLastStage()) {
				nextStage = currStage.getNextStage();
		} else if (!p_isApproved) {
			nextStage = currStage.getPreviousStage();
//		} else if (p_isApproved && currStage.getNextStage() == null) {
		} else if (p_isApproved && currStage.isLastStage()) {
			nextStage = MAGRStage.getFirstStage(getCtx(), currStage.getAGR_Agreement_ID(), get_TrxName());
		}
		
		firstStage = MAGRStage.getFirstStage(getCtx(), currStage.getAGR_Agreement_ID(), get_TrxName());
		C_BPartner_ID_From = firstStage.getSigners(p_AD_Table_ID, Record_ID);
//		MAGRApprovalList al = new MAGRApprovalList(getCtx(), nextStage.getAGR_Agreement_ID(), get_TrxName());
		ArrayList<MAGRAgreementList> agrList = MAGRAgreementList.getOfStage(getCtx(), get_TrxName(), p_AD_Table_ID, Record_ID);	// new MAGRAgreementList(getCtx(), al.getAGR_ApprovalList_ID(), get_TrxName()); 
//		C_BPartner_ID_To = nextStage.getSigners(p_AD_Table_ID, Record_ID);
		C_BPartner_ID_To = agrList.get(0).getSigner_ID();
		application = new X_TRM_Application(getCtx(), Record_ID, get_TrxName());
		contract = new X_CMS_Contract(getCtx(), application.getCMS_Contract_ID(), get_TrxName());
	}

	/*
     */
	@Override
	protected String doIt() throws Exception {

		MAttachmentEntry entry = Util.getAttachment(pi, m_ctx, templateName);
		if (entry == null)
			throw new AdempiereException(Msg.translate(m_ctx,
					"NotFoundTemplate") + " " + templateName);

		File inputFile = Util.getAttachmentEntryFile(entry);

		Workbook tableBook = null;
		Sheet sheet = null;
		try {
			tableBook = Workbook.getWorkbook(inputFile);
			sheet = tableBook.getSheet(0);
		} catch (Exception e) {
			ADialog.error(999, null, "Error tableBook. " + e.getMessage());
			return "Error tableBook.";
		}

		ExcelCell cellSubject = Util.getCellStart(tableBook, "sub");
		ExcelCell cellMessageIsApproved = Util.getCellStart(tableBook, "messisapproved");
		ExcelCell cellMessageIsNotApproved = Util.getCellStart(tableBook, "messisnotapproved");
		ExcelCell cellMessageIsApprovedAll = Util.getCellStart(tableBook, "messisapprovedall");
		ExcelCell cellSignature = Util.getCellStart(tableBook, "sign");

		String subject = sheet.getCell(cellSubject.getC() + 1, cellSubject.getR()).getContents();
		String textMailIsApproved = sheet.getCell(cellMessageIsApproved.getC() + 1, cellMessageIsApproved.getR()).getContents();
		String textMailIsNotApproved = sheet.getCell(cellMessageIsNotApproved.getC() + 1, cellMessageIsNotApproved.getR()).getContents();
		String textMailIsApprovedAll = sheet.getCell(cellMessageIsApprovedAll.getC() + 1, cellMessageIsApprovedAll.getR()).getContents();
		String signature = sheet.getCell(cellSignature.getC() + 1, cellSignature.getR()).getContents();

		/*
		 * Params: 
		 * {0} - бюджетная заявка; 
		 * {1} - ФИО отправителя; 
		 * {2} - рабочая
		 * редакция;
		 */

		StringBuffer msgHtml = new StringBuffer();
		String textMail = null;
		Object[] param = null;
//		if (p_isApproved && currStage.getNextStage() != null) {
		if (p_isApproved && !currStage.isLastStage()) {
			param = new Object[] {application.getDocumentNo(), 
					(new MBPartner(getCtx(), C_BPartner_ID_From.get(0), get_TrxName()).getName()),	
					contract.getCMS_Contract_ContractNum() + " " + new SimpleDateFormat("dd.MM.yyyy").format(contract.getCMS_Contract_CreatDate())};
			textMail = textMailIsApproved;
		} else if (!p_isApproved) {
			param = new Object[] {application.getDocumentNo(), 
					(new MBPartner(getCtx(), (new MUser(getCtx(), AD_User_ID, get_TrxName()).getC_BPartner_ID()), get_TrxName()).getName()),	
					contract.getCMS_Contract_ContractNum() + " " + new SimpleDateFormat("dd.MM.yyyy").format(contract.getCMS_Contract_CreatDate())};
			textMail = textMailIsNotApproved;
//		} else if (p_isApproved && currStage.getNextStage() == null) {
		} else if (p_isApproved && currStage.isLastStage()) {
			param = new Object[] {application.getDocumentNo(), 
					(new MBPartner(getCtx(), (new MUser(getCtx(), AD_User_ID, get_TrxName()).getC_BPartner_ID()), get_TrxName()).getName()),	
					contract.getCMS_Contract_ContractNum() + " " + new SimpleDateFormat("dd.MM.yyyy").format(contract.getCMS_Contract_CreatDate())};
			textMail = textMailIsApprovedAll;
		}

		MUser[] userFrom = MUser.getOfBPartner(m_ctx, C_BPartner_ID_From.get(0), get_TrxName());
		MUser[] userTo = MUser.getOfBPartner(m_ctx, C_BPartner_ID_To, get_TrxName());
		
		// message HTML
		msgHtml.append("<table border=\"center\" width=\"80%\"> \n")
				.append("<tr> \n")
				.append("     <td align=\"center\"> \n")
				.append("          <font size=\"4\">Уведомление</font> ")
				.append("     </td> \n")
				.append("</tr> \n")
				.append("<tr> \n")
				.append("     <td> \n")
				.append("          <pre> \n")
				.append(textMail)
				.append("          </pre> \n")
				.append("     </td> \n")
				.append("</tr> \n")
				.append("<tr> \n")
				.append("     <td align=\"right\"><font size=\"1\">")
				.append(signature)
				.append("</font></td> \n")
				.append("</tr> \n")
				.append("</table>");

		for (int i = 0; i < userTo.length; i++) {
			if (userTo[i].getAD_User_ID() != 0 && 
					userTo[i].getEMail() != null && 
					userTo[i].getEMail().length() != 0) {
				Util.sendMail(userTo[i].getAD_User_ID(), 
						userFrom[i].getAD_User_ID(), 
						MessageFormat.format(subject, param), 
						MessageFormat.format(msgHtml.toString(), param), true);
			}
		}

		tableBook.close();
		inputFile.delete();

		return Msg.translate(m_ctx, "Success");
	}

}